package com.example.cash.craft.controller;

import com.example.cash.craft.pojo.core.CurrentPrincipal;
import com.example.cash.craft.pojo.param.UserLoginParam;
import com.example.cash.craft.security.PassportService;
import com.example.cash.craft.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "1. 用户认证模块")
@RestController
@RequestMapping("/api/passport")
public class PassportController {

    @Autowired
    private PassportService passportService;

    @ApiOperationSupport(order = 20)
    @Operation(summary = "[游客] 用户登录")
    @PostMapping("/login")
    public JsonResult<CurrentPrincipal> login(@ParameterObject @Valid UserLoginParam param,
                                              HttpServletRequest request, HttpServletResponse response) {
        CurrentPrincipal currentPrincipal = passportService.login(param);
        return JsonResult.ok(currentPrincipal);
    }

    @ApiOperationSupport(order = 30)
    @Operation(summary = "[用户] 退出登录")
    @PostMapping("/logout")
    public JsonResult logout() {
        passportService.logout();
        return JsonResult.ok();
    }

    @ApiOperationSupport(order = 90)
    @Operation(summary = "[用户] 测试-通过认证")
    @GetMapping("/test/authenticate")
    public JsonResult<String> testAuthenticate() {
        return JsonResult.ok("通过认证（判定为已登录）");
    }

    @ApiOperationSupport(order = 91)
    @Operation(summary = "[用户] 测试-识别当事人")
    @GetMapping("/test/principal")
    public JsonResult<CurrentPrincipal> testPrincipal(@AuthenticationPrincipal CurrentPrincipal principal) {
        return JsonResult.ok(principal);
    }

    @ApiOperationSupport(order = 92)
    @Operation(summary = "[用户] 测试-检查管理员权限")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @GetMapping("/test/authority")
    public JsonResult<CurrentPrincipal> testAuthority(@AuthenticationPrincipal CurrentPrincipal principal) {
        return JsonResult.ok(principal);
    }

}